/**
 *
 */
package com.hand.cloud.b2b.daos.impl;

import de.hybris.platform.catalog.CatalogVersionService;
import de.hybris.platform.core.Registry;
import de.hybris.platform.jalo.JaloSession;
import de.hybris.platform.jalo.user.UserManager;
import de.hybris.platform.product.ProductService;
import de.hybris.platform.servicelayer.exceptions.ModelSavingException;
import de.hybris.platform.servicelayer.model.ModelService;
import de.hybris.platform.servicelayer.search.FlexibleSearchQuery;
import de.hybris.platform.servicelayer.search.FlexibleSearchService;
import de.hybris.platform.servicelayer.session.Session;
import de.hybris.platform.servicelayer.session.SessionService;
import de.hybris.platform.servicelayer.user.UserService;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.hand.cloud.b2b.daos.EPOrderDAO;
import com.hand.cloud.b2b.daos.TBTradeDAO;
import com.hand.cloud.b2b.model.EPOrderModel;
import com.hand.cloud.b2b.model.TB_LogisticsTagModel;
import com.hand.cloud.b2b.model.TB_OrderModel;
import com.hand.cloud.b2b.model.TB_PromotionDetailModel;
import com.hand.cloud.b2b.model.TB_ServiceOrderModel;
import com.hand.cloud.b2b.model.TB_TradeModel;
import com.hand.cloud.b2b.services.OrderService;
import com.taobao.api.domain.Order;
import com.taobao.api.domain.Trade;


/**
 * @author StephenWang
 * @Time Aug 14, 20142:27:57 PM
 */
@Component(value = "tbTradeDAO")
public class DefaultTBTradeDAO implements TBTradeDAO
{

	public static Logger LOG = Logger.getLogger(DefaultTBTradeDAO.class);

	@Autowired
	private ModelService modelService;
	@Autowired
	private EPOrderDAO epOrderDAO;

	private OrderService orderService;

	@Autowired
	private CatalogVersionService catalogVersionService;

	@Autowired
	private FlexibleSearchService flexibleSearchService;

	@Autowired
	private UserService userService;

	@Autowired
	private ProductService productService;

	@Autowired
	private SessionService sessionService;


	/**
	 * 将淘宝返回对象转化为TB_Trade
	 * 
	 * @param trade
	 * @return
	 */
	public TB_TradeModel createTBTrade(final Trade trade)
	{
		// 设置默认CatalogVersion
		setDefaultCatalogVersion();

		final TB_TradeModel tbTrade = this.modelService.create(TB_TradeModel.class);
		// 1
		tbTrade.setSeller_nick(trade.getSellerNick());
		tbTrade.setPic_path(trade.getPicPath());
		tbTrade.setPayment(trade.getPayment());
		tbTrade.setSnapshot_url(trade.getSnapshotUrl());
		tbTrade.setSeller_rate(trade.getSellerRate());

		//2
		tbTrade.setPost_fee(trade.getPostFee());
		tbTrade.setBuyer_alipay_no(trade.getBuyerAlipayNo());
		tbTrade.setReceiver_name(trade.getReceiverName());
		tbTrade.setReceiver_state(trade.getReceiverState());
		tbTrade.setReceiver_address(trade.getReceiverAddress());

		//3
		tbTrade.setReceiver_zip(trade.getReceiverZip());
		tbTrade.setReceiver_mobile(trade.getReceiverMobile());
		tbTrade.setReceiver_phone(trade.getReceiverPhone());
		tbTrade.setConsign_time(trade.getConsignTime());
		tbTrade.setSeller_alipay_no(trade.getSellerAlipayNo());

		//4
		tbTrade.setSeller_mobile(trade.getSellerMobile());
		tbTrade.setSeller_phone(trade.getSellerPhone());
		tbTrade.setSeller_name(trade.getSellerName());
		tbTrade.setSeller_email(trade.getSellerEmail());
		tbTrade.setAvailable_confirm_fee(trade.getAvailableConfirmFee());

		//5
		tbTrade.setReceived_payment(trade.getReceivedPayment());
		tbTrade.setTimeout_action_time(trade.getTimeoutActionTime());
		tbTrade.setIs_3D(trade.getIs3D());
		trade.setOrders(trade.getOrders());
		trade.setPromotion(trade.getPromotion());

		//6
		tbTrade.setPromotion_details((TB_PromotionDetailModel) trade.getPromotionDetails());
		tbTrade.setTid(trade.getTid());
		tbTrade.setNum(trade.getNum());
		tbTrade.setNum_iid(trade.getNumIid());
		tbTrade.setStatus(trade.getStatus());

		//7
		tbTrade.setTitle(trade.getTitle());
		tbTrade.setType(trade.getType());
		tbTrade.setPrice(trade.getPrice());
		tbTrade.setSeller_cod_fee(trade.getSellerCodFee());
		tbTrade.setDiscount_fee(trade.getDiscountFee());

		//8
		tbTrade.setPoint_fee(trade.getPointFee());
		tbTrade.setHas_post_fee(trade.getHasPostFee());
		tbTrade.setTotal_fee(trade.getTotalFee());
		tbTrade.setIs_lgtype(trade.getIsLgtype());
		tbTrade.setIs_brand_sale(trade.getIsBrandSale());

		//9
		tbTrade.setIs_force_wlb(trade.getIsForceWlb());
		tbTrade.setCreated(trade.getCreated());
		tbTrade.setPay_time(trade.getPayTime());
		tbTrade.setModified(trade.getModified());
		tbTrade.setEnd_time(trade.getEndTime());

		//10
		tbTrade.setBuyer_message(trade.getBuyerMessage());
		tbTrade.setAlipay_id(trade.getAlipayId());
		tbTrade.setAlipay_no(trade.getAlipayNo());
		tbTrade.setBuyer_memo(trade.getBuyerMemo());
		tbTrade.setBuyer_flag(trade.getBuyerFlag());

		//11
		tbTrade.setSeller_memo(trade.getSellerMemo());
		tbTrade.setSeller_flag(trade.getSellerFlag());
		tbTrade.setInvoice_name(trade.getInvoiceName());
		tbTrade.setInvoice_type(trade.getInvoiceName());
		tbTrade.setBuyer_nick(trade.getBuyerNick());
		tbTrade.setBuyer_area(trade.getBuyerArea());

		//12
		tbTrade.setBuyer_email(trade.getBuyerEmail());
		tbTrade.setHas_yfx(trade.getHasYfx());
		tbTrade.setYfx_fee(trade.getYfxFee());
		tbTrade.setYfx_id(trade.getYfxId());
		tbTrade.setYfx_type(trade.getYfxType());

		//13
		tbTrade.setCredit_card_fee(trade.getCreditCardFee());
		tbTrade.setStep_trade_status(trade.getStepTradeStatus());
		tbTrade.setStep_paid_fee(trade.getStepPaidFee());
		tbTrade.setMark_desc(trade.getMarkDesc());
		tbTrade.setEticket_ext(trade.getEticketExt());

		//14
		tbTrade.setSend_time(trade.getSendTime());
		tbTrade.setShipping_type(trade.getShippingType());
		tbTrade.setBuyer_cod_fee(trade.getBuyerCodFee());
		tbTrade.setExpress_agency_fee(trade.getExpressAgencyFee());
		tbTrade.setAdjust_fee(trade.getAdjustFee());

		//15
		tbTrade.setBuyer_obtain_point_fee(trade.getBuyerObtainPointFee());
		tbTrade.setCod_fee(trade.getCodFee());
		tbTrade.setTrade_from(trade.getTradeFrom());
		tbTrade.setCod_status(trade.getCodStatus());
		tbTrade.setCan_rate(trade.getCanRate());

		//16
		tbTrade.setService_orders((TB_ServiceOrderModel) trade.getServiceOrders());
		tbTrade.setCommission_fee(trade.getCommissionFee());
		tbTrade.setTrade_memo(trade.getTradeMemo());
		tbTrade.setBuyer_rate(trade.getBuyerRate());
		tbTrade.setTrade_source(trade.getTradeSource());

		//17
		tbTrade.setSeller_can_rate(trade.getSellerCanRate());
		tbTrade.setIs_part_consign(trade.getIsPartConsign());
		tbTrade.setIs_daixiao(trade.getIsDaixiao());
		tbTrade.setReal_point_fee(trade.getRealPointFee());
		tbTrade.setReceiver_city(trade.getReceiverCity());

		//18
		tbTrade.setReceiver_district(trade.getReceiverDistrict());
		tbTrade.setArrive_interval(trade.getArriveInterval());
		tbTrade.setArrival_cut_time(trade.getArriveCutTime());
		tbTrade.setConsign_interval(trade.getConsignInterval());
		tbTrade.setService_tags((TB_LogisticsTagModel) trade.getServiceTags());

		//19
		tbTrade.setO2o(trade.getO2o());
		tbTrade.setO2o_guide_id(trade.getO2oGuideId());
		tbTrade.setO2o_shop_id(trade.getO2oShopId());
		tbTrade.setO2o_guide_name(trade.getO2oGuideName());
		tbTrade.setO2o_shop_name(trade.getO2oShopName());

		//20
		tbTrade.setO2o_delivery(trade.getO2oDelivery());
		tbTrade.setZero_purchase(trade.getZeroPurchase());
		tbTrade.setAlipay_point(trade.getAlipayPoint());
		tbTrade.setPcc_af(trade.getPccAf());
		tbTrade.setO2o_out_trade_id(trade.getO2oOutTradeId());
		tbTrade.setIs_wt(trade.getIsWt());


		final List<TB_OrderModel> orders = new ArrayList<TB_OrderModel>();

		for (final Order order : trade.getOrders())
		{
			final TB_OrderModel tbOrder = createTBOrder(order);
			tbOrder.setTrade(tbTrade);

			try
			{
				this.modelService.save(tbOrder);
			}
			catch (final ModelSavingException e)
			{
				e.printStackTrace();
				LOG.info("-----------createTBTrade tbOrder Error!----------");
			}

			orders.add(tbOrder);
		}

		tbTrade.setOrders(orders);

		try
		{
			this.modelService.save(tbTrade);
		}
		catch (final ModelSavingException e)
		{
			e.printStackTrace();
			LOG.info("-----------createTBTrade Error!----------");
		}

		return tbTrade;
	}

	/**
	 * 
	 * @param order
	 */
	public TB_OrderModel createTBOrder(final Order order)
	{
		final TB_OrderModel tbOrder = this.modelService.create(TB_OrderModel.class);

		//1
		tbOrder.setItem_meal_name(order.getItemMealName());
		tbOrder.setPic_path(order.getPicPath());
		tbOrder.setSeller_nick(order.getSellerNick());
		tbOrder.setBuyer_nick(order.getBuyerNick());
		tbOrder.setRefund_status(order.getRefundStatus());

		//2
		tbOrder.setOuter_iid(order.getOuterIid());
		tbOrder.setSnapshot_url(order.getSnapshotUrl());
		tbOrder.setTimeout_action_time(order.getTimeoutActionTime());
		tbOrder.setBuyer_rate(order.getBuyerRate());
		tbOrder.setSeller_rate(order.getSellerRate());

		//3
		tbOrder.setSeller_type(order.getSellerType());
		tbOrder.setCid(order.getCid());
		tbOrder.setOid(order.getOid());
		tbOrder.setStatus(order.getStatus());
		tbOrder.setTitle(order.getTitle());

		//4
		tbOrder.setPrice(order.getPrice());
		tbOrder.setNum_iid(order.getItemMealId());
		tbOrder.setItem_meal_id(order.getItemMealId());
		tbOrder.setSku_id(order.getSkuId());
		tbOrder.setNum(order.getNum());

		//5
		tbOrder.setOuter_sku_id(order.getOuterSkuId());
		tbOrder.setOrder_from(order.getOrderFrom());
		tbOrder.setTotal_fee(order.getTotalFee());
		tbOrder.setPayment(order.getPayment());
		tbOrder.setDiscount_fee(order.getDiscountFee());

		//6
		tbOrder.setAdjust_fee(order.getAdjustFee());
		tbOrder.setModified(order.getModified());
		tbOrder.setSku_properties_name(order.getSkuPropertiesName());
		tbOrder.setRefund_id(order.getRefundId());
		tbOrder.setIs_oversold(order.getIsOversold());

		//7
		tbOrder.setIs_service_order(order.getIsServiceOrder());
		tbOrder.setEnd_time(order.getEndTime());
		tbOrder.setConsign_time(order.getConsignTime());
		tbOrder.setShipping_type(order.getShippingType());
		tbOrder.setBind_oid(order.getBindOid());

		//8
		tbOrder.setLogistics_company(order.getLogisticsCompany());
		tbOrder.setInvoice_no(order.getInvoiceNo());
		tbOrder.setIs_daixiao(order.getIsDaixiao());
		tbOrder.setDivide_order_fee(order.getDivideOrderFee());
		tbOrder.setPart_mjz_discount(order.getPartMjzDiscount());

		//9
		tbOrder.setTicket_outer_id(order.getTicketOuterId());
		tbOrder.setTicket_expdate_key(order.getTicketExpdateKey());
		tbOrder.setStore_code(order.getStoreCode());
		tbOrder.setIs_www(order.getIsWww());

		try
		{
			this.modelService.save(tbOrder);
		}
		catch (final ModelSavingException e)
		{
			e.printStackTrace();
			LOG.info("-----------createTBOrder Error!----------");
		}

		return tbOrder;
	}


	/**
	 * 获取TB_Trade
	 * 
	 * @param pk
	 * @return
	 */
	@Override
	public TB_TradeModel getTradeByPK(final String pk)
	{

		TB_TradeModel trade = null;

		final StringBuffer queryStr = new StringBuffer("");
		queryStr.append("select {p.pk} ").append("from {tb_trade as p} ").append("where {p.pk} = ?pk");

		final FlexibleSearchQuery query = new FlexibleSearchQuery(queryStr.toString());
		query.addQueryParameter("pk", pk);

		LOG.info("----queryStr:" + query.getQuery());

		try
		{
			trade = this.flexibleSearchService.searchUnique(query);
			LOG.info("-----getTotal_fee:" + trade.getTotal_fee());
		}
		catch (final Exception e)
		{
			e.printStackTrace();
			return null;
		}

		return trade;
	}


	/**
	 * 设置默认CatalogVersion
	 */
	public void setDefaultCatalogVersion()
	{
		if (!Registry.hasCurrentTenant())
		{
			System.out.println("************ has no CurrentTenant");
			Registry.activateMasterTenant();
		}

		//		final UserModel userModel = userService.getCurrentUser();
		//		if (userModel != null)
		//		{
		//			System.out.println("************ userModel is null");
		//			userService.setCurrentUser(userService.getAdminUser());
		//		}

		Session session = null;
		if (!sessionService.hasCurrentSession())
		{
			System.out.println("**********has no session");
			session = sessionService.createNewSession();
		}
		else
		{
			session = sessionService.getCurrentSession();
		}

		System.out.println("**********currentSession:" + session);
		System.out.println("**********sessionService:" + sessionService);

		JaloSession.getCurrentSession().setUser(UserManager.getInstance().getAdminEmployee());

		System.out.println("modelService:" + modelService);

		if (modelService == null)
		{
			modelService = (ModelService) Registry.getApplicationContext().getBean("defaultModelService");
			System.out.println("result modelService:" + modelService);
		}

		//this.catalogVersionService.setSessionCatalogVersion(DefaultProperties.CATALOG_ID, DefaultProperties.CATALOGVAERSION_NAME);
	}

	/**
	 * @return the orderService
	 */
	public OrderService getOrderService()
	{
		return orderService;
	}

	/**
	 * @param orderService
	 *           the orderService to set
	 */
	public void setOrderService(final OrderService orderService)
	{
		this.orderService = orderService;
	}


	/**
	 * 更新TB_Order订单的状态
	 * 
	 * @return
	 */

	@Override
	public void changeTBTradeStatus(final EPOrderModel epOrder)
	{
		// YTODO Auto-generated method stub
		final String pk = epOrder.getSourcePk();
		final TB_TradeModel tbTrade = this.getTradeByPK(pk);
		tbTrade.setStatus(epOrder.getStatus());
		//		final TB_OrderModel tbOrder = this.getOrderByPK(pk);
		//		tbOrder.setStatus(epOrder.getStatus());
	}

	/**
	 * 获取TB_Order
	 * 
	 * @param pk
	 * @return TB_OrderModel
	 */
	@Override
	public TB_OrderModel getOrderByPK(final String pk)
	{
		TB_OrderModel order = null;

		final StringBuffer queryStr = new StringBuffer("");
		queryStr.append("select {p.pk} ").append("from {tb_order as p} ").append("where {p.pk} = ?pk");

		final FlexibleSearchQuery query = new FlexibleSearchQuery(queryStr.toString());
		query.addQueryParameter("pk", pk);

		LOG.info("----queryStr:" + query.getQuery());

		try
		{
			order = this.flexibleSearchService.searchUnique(query);
		}
		catch (final Exception e)
		{
			e.printStackTrace();
			return null;
		}

		return order;
	}
}